const mongoose = require('mongoose')
const Common = require('../util/common')
let GameUserModel = mongoose.models['GameUser']
let StaticsModel = mongoose.models['Statics']

module.exports = {
    async init(){
        let cron = require('node-cron');
        let self = this;
        cron.schedule('0 0 * * * *', async function(){
            await self.saveUserInfoToStaticsHour();
        });
    },
    _getInitStatics(type,channel){
        let data = new Date()
        let statics = {
            type :type,
            timeId: (data.getFullYear()+'-'+(data.getMonth()+1)+'-'+data.getDate()+'-'+data.getHours()),
            newUser: 0,
            activeUser: 0,
            _secondNew : -1, //临时存放2天前注册用户
            _seventhNew : -1,//临时存放七天前注册用户
            _monthNew : -1,//临时存放30天前注册用户
            _secondRemain : 0, //临时存放次留
            _seventhRemain : 0, //临时存放七留
            _monthRemain : 0, //临时存放月留
            secondRemain : 0,
            seventhRemain : 0,
            monthRemain : 0,
            channel: channel,
            onLineTime : 0,
            events: []
        }
        return statics;
    },
    _getEvent(stats,key){
        for(let i=0; i<stats.events.length; i++){
            if(stats.events[i].key == key){
                return stats.events[i];
            }
        }
        let event = {
             key : key,
            value : 0
        }
        stats.events.push(event)
        return event
    },
    async saveUserInfoToStaticsHour(){
        console.log('saveUserInfoToStaticsHour:',Date.now());
        let _data = new Date()
        let date = _data.getTime()
        let lastHourTime = new Date(date-60*60*1000)
        let allActiveUser = await GameUserModel.find({lastLoginTick:{$gte:lastHourTime.getTime()}});
        this.statics = [];

        for(let i=0; i<allActiveUser.length; i++){
            let user = allActiveUser[i];
            let channel = user.referrerInfoAppId?user.referrerInfoAppId:'0'
            if(!this.statics[channel]){
                this.statics[channel] = this._getInitStatics(0,channel)
            }
            let stats = this.statics[channel]
            if(user.registerTimeTick > lastHourTime && user.registerTimeTick < date){ //新增
                stats.newUser++
            }
            if(user.lastLoginTick > lastHourTime && user.lastLoginTick < date){ //活跃
                stats.activeUser++
            }
            stats.onLineTime += user.onLineTime;
            user.onLineTime = 0;

            for(let j=0; j<user.events.length; j++){    //事件
                let event = this._getEvent(stats,user.events[j].key);
                event.value += user.events[j].value;
            }
            user.events = [];

            let day = Common.calcDetailDay(new Date(user.registerTimeTick),new Date(user.lastLoginTick))
            if(day == 1){
                stats._secondRemain ++;
            } else if(day == 6){
                stats._seventhRemain++;
            } else if(day == 29){
                stats._monthRemain++;
            }

            if(stats._secondNew == -1){
                let lastTime = date-24*3600*1000;
                let ld = new Date(lastTime);
                let minLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate())
                let maxLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate()+' 23:59:59')
                let uss = await GameUserModel.find({registerTimeTick:{$gt:minLastTime,$lte:maxLastTime}});
                !!uss ? stats._secondNew = uss.length : stats._secondNew = 0
            }
            if(stats._seventhNew == -1){
                let lastTime = date-7*24*3600*1000;
                let ld = new Date(lastTime);
                let minLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate())
                let maxLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate()+' 23:59:59')
                let uss = await GameUserModel.find({referrerInfoAppId:user.referrerInfoAppId, registerTimeTick:{$gt:minLastTime,$lte:maxLastTime}});
                !!uss ? stats._seventhNew = uss.length : stats._seventhNew = 0
            }
            if(stats._monthNew == -1){
                let lastTime = date-29*24*3600*1000;
                let ld = new Date(lastTime);
                let minLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate())
                let maxLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate()+' 23:59:59')
                let uss = await GameUserModel.find({referrerInfoAppId:user.referrerInfoAppId, registerTimeTick:{$gt:minLastTime,$lte:maxLastTime}});
                !!uss ? stats._monthNew = uss.length : stats._monthNew = 0
            }

            await user.save()
        }
        for(let i=0; i<this.statics.length; i++){
            let stats = this.statics[i];
            stats.secondRemain = stats._secondNew==0?stats._secondNew: stats._secondRemain / stats._secondNew;
            stats.seventhRemain = stats._seventhNew==0?stats._seventhNew:stats._seventhRemain / stats._seventhNew;
            stats.monthRemain = stats._monthNew==0?stats._monthNew:stats._monthRemain / stats._monthNew;
            await StaticsModel.create(stats);
        }
        if(new Date().getHours() == 0){
            await saveUserInfoToStaticsDay();
        }
        console.log('hour end')
    },
    async saveUserInfoToStaticsDay(){
        let _data = new Date()
        let date = _data.getTime()
        console.log('day start')
        let lastHourTime = new Date(date-24*60*60*1000)
        let allActiveUser = await GameUserModel.find({lastLoginTick:{$gte:lastHourTime.getTime()}});
        this.statics = [];
        console.log('allActiveUser:',allActiveUser.length)
        let allNewUser = 0;
        for(let i=0; i<allActiveUser.length; i++){
            let user = allActiveUser[i];
            let channel = user.referrerInfoAppId?user.referrerInfoAppId:'0'
            if(!this.statics[channel]){
                this.statics[channel] = this._getInitStatics(1,channel)
            }
            let stats = this.statics[channel]
            if(user.registerTimeTick > lastHourTime && user.registerTimeTick < date){ //新增
                stats.newUser++
                allNewUser++;
            }
            if(user.lastLoginTick > lastHourTime && user.lastLoginTick < date){ //活跃
                stats.activeUser++
            }
            let day = Common.calcDetailDay(new Date(user.registerTimeTick),new Date(user.lastLoginTick))
            if(day == 1){
                stats._secondRemain ++;
            } else if(day == 6){
                stats._seventhRemain++;
            } else if(day == 29){
                stats._monthRemain++;
            }

            if(stats._secondNew == -1){
                let lastTime = date-24*3600*1000;
                let ld = new Date(lastTime);
                let minLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate())
                let maxLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate()+' 23:59:59')
                let uss = await GameUserModel.find({registerTimeTick:{$gt:minLastTime,$lte:maxLastTime}});
                !!uss ? stats._secondNew = uss.length : stats._secondNew = 0
            }
            if(stats._seventhNew == -1){
                let lastTime = date-7*24*3600*1000;
                let ld = new Date(lastTime);
                let minLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate())
                let maxLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate()+' 23:59:59')
                let uss = await GameUserModel.find({referrerInfoAppId:user.referrerInfoAppId, registerTimeTick:{$gt:minLastTime,$lte:maxLastTime}});
                !!uss ? stats._seventhNew = uss.length : stats._seventhNew = 0
            }
            if(stats._monthNew == -1){
                let lastTime = date-29*24*3600*1000;
                let ld = new Date(lastTime);
                let minLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate())
                let maxLastTime = Date.parse(ld.getFullYear()+'-'+(ld.getMonth()+1)+'-'+ld.getDate()+' 23:59:59')
                let uss = await GameUserModel.find({referrerInfoAppId:user.referrerInfoAppId, registerTimeTick:{$gt:minLastTime,$lte:maxLastTime}});
                !!uss ? stats._monthNew = uss.length : stats._monthNew = 0
            }
            await user.save()
        }


        for(let i=0; i<this.statics.length; i++){
            let stats = this.statics[i];
            stats.secondRemain = stats._secondNew==0?stats._secondNew: stats._secondRemain / stats._secondNew;
            stats.seventhRemain = stats._seventhNew==0?stats._seventhNew:stats._seventhRemain / stats._seventhNew;
            stats.monthRemain = stats._monthNew==0?stats._monthNew:stats._monthRemain / stats._monthNew;
            for(let j=1; j<=24; j++){ //把时间段的数据综合一下
                let timeId= _data.toLocaleDateString()+'-'+j
                let timestat = await StaticsModel.findOne({timeId:timeId});
                if(timestat){
                    stats.onLineTime += timestat.onLineTime;
                    for(let k=0; k<timestat.events.length; k++){    //事件
                        let event = this._getEvent(stats,timestat.events[k].key);
                        event.value += timestat.events[k].value;
                    }
                }
            }
            await StaticsModel.create(this.statics[i]);
        }
    }
}